<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise.resolve()缓存后台数据</title>
</head>
<body>
    <script>
        // Promise.resolve请求成功的函数
        Promise.resolve("后盾人").then(
            value => {
                console.log(value);
            }
        )

        // Promise.resolve的内部原理
        Promise.hd = function (value){
            return new Promise(resolve => {
                resolve(value);
            })
        }

        Promise.hd("hd").then(
            value => {
                console.log(value);
            }
        )


        // 例：缓存后台数据
        function ajax(url){
            return new Promise((resolve,reject) => {
                if(!/^http/.test(url)){
                    throw new ParamError("请求地址格式错误");
                }

                let xhr = new XMLHttpRequest();
                xhr.open("GET",url);
                xhr.send();
                xhr.onload = function(){
                    if(this.status == 200){
                        resolve(JSON.parse(this.response));
                    }else if(this.status == 404){
                        reject(new HttpError("请求参数错误"));
                    }else{
                        reject("加载失败");
                    }
                };
                xhr.onerror = function (){
                    reject(this);
                }
            })
        }

        function query(type){
            const cache = query.cache || (query.cache = new Map());
            if(cache.has(type)){
                console.log("走缓存");
                return Promise.resolve(cache.get(type));
            }
            return ajax(`http://localhost:8008/index.php/api/home/getJiaDianList?type=${type}`).then(
                value => {
                    console.log("没走缓存");
                    cache.set(type,value);
                    return value;
                }
            ).catch(
                error => console.log(error)
            )
        }

        query(3).then(
            value => {
                console.log(value);
            }
        );

        setTimeout(() => {
            query(3).then(
                value => console.log(value)
            );
        },1000);
    </script>
</body>
</html>